/**
 * 解析json字符串
 * 
 * @param text  json字符串
 * @param def   默认值
 * @returns 
 */
export function parse<T>(text: string, def?: T): T {
  try {
    return JSON.parse(text)
  }
  catch(error) {
    if (def) {
      return def
    }
    throw new Error('解析JSON失败; ' + text)
  }
}

function sortProps(obj: unknown): unknown {
    if (Array.isArray(obj)) {
      return obj.map(sortProps)
    }
    if (typeof obj === 'object') {
      return Object.keys(obj as object)
        .sort().reduce((res, key) => {
          res[key] = (obj as any)[key]
          return res
        }, {} as any)
    }
    return obj
  }

/**
 * 转json字符串，属性按照升序排序
 * 
 * @param obj 
 * @returns 
 */
export function toSortedString(obj: unknown): string {
  return JSON.stringify(sortProps(obj))
}